<template>
<Modal :mask-closable="false" v-model="showModal" :title="injectData.edit ? '编辑歌曲':'新增歌曲'" @on-ok="ok" :loading="modalLoading" class="add-music-modal">
	<Row>
		<Col span="16">
		<Form ref="addMusicForm" :model="addMusicForm" :rules="addMusicFormRule" :label-width="80">
			<Row>
				<Col span="6">
				<header-img-uploader :img-upload-path="imgUploadUrl" :upload-img-data="uploadImgData" @on-upload-success="uploadImgSuccess" :show-img-path="uploadImgCallbackPath"></header-img-uploader>
				<Upload type="drag" :action="uploadMuiscUrl" accept="audio/mpeg,audio/x-wav" :data="uploadMusicData" :show-upload-list="false" :before-upload="beforeMusicUpload" :headers="{'Access-Control-Allow-Origin':'*'}" :on-success="uploadMusicSuccess" :on-error="uploadMusicError"
				    :on-progress="uploadMusicProgressFunc" :format="['wav']" :on-format-error="handleMusicFormatError" class="upload-music-box">
					<Icon type="music-note" size="52" :color="callBackTone_quality_list?'#3399ff':'rgba(0,0,0,.2)'"></Icon>
					<transition name="fade">
						<div class="progress" v-if="isUploading">{{uploadProgress}}%</div>
					</transition>
					<div slot="tip" class="tip-text" v-if="!callBackTone_quality_list">上传音频</div>
				</Upload>
				</Col>
				<Col span="18">
				<FormItem prop="name" label="歌曲名称">
					<Input v-model="addMusicForm.name" placeholder="输入歌曲名称(如未填写，音频上传成功后自动填写)"></Input>
				</FormItem>
				<FormItem prop="singer_uuid" label="演唱">
					<author-selector v-model="addMusicForm.singer_uuid" :inject-data="addMusicForm.singer_obj" placeholder="选择演唱者"></author-selector>
				</FormItem>
				<FormItem prop="lyric_uuid" label="作词">
					<author-selector v-model="addMusicForm.lyric_uuid" :inject-data="addMusicForm.lyric_obj" placeholder="选择作词者"></author-selector>
				</FormItem>
				<FormItem prop="composer_uuid" label="作曲">
					<author-selector v-model="addMusicForm.composer_uuid" :inject-data="addMusicForm.composer_obj" placeholder="选择作曲者"></author-selector>
				</FormItem>
				<FormItem label="音质选择" prop="tone_quality_list">
					<CheckboxGroup v-model="addMusicForm.tone_quality_list">
						<Checkbox label="liuchang" :disabled="injectData.edit ?  !tone_qualist_all.liuchang : !callBackTone_quality_list">流畅音质</Checkbox>
						<Checkbox label="biaozhun" :disabled="injectData.edit ? !tone_qualist_all.biaozhun : !callBackTone_quality_list">标准音质</Checkbox>
						<Checkbox label="gaopin" :disabled="injectData.edit ?  !tone_qualist_all.gaopin : !callBackTone_quality_list">高品音质</Checkbox>
						<Checkbox label="wusun" :disabled="injectData.edit ? !tone_qualist_all.wusun : !callBackTone_quality_list">无损音质</Checkbox>
					</CheckboxGroup>
				</FormItem>
				<FormItem label="是否上线" prop="is_online">
					<i-switch v-model="addMusicForm.isOnline"></i-switch>
				</FormItem>
				<FormItem label="售价">
					<InputNumber :min="0" :step="1" :precision="2" v-model="addMusicForm.sale_price"></InputNumber>
				</FormItem>
				<FormItem label="歌词">
					<Upload :action="lrcUploadUrl" :data="uploadLrcData" :format="['lrc']" :on-format-error="handleFormatError" v-if="injectData.edit || !addMusicForm.lyric_file_url" :headers="{'Access-Control-Allow-Origin':'*'}" :on-success="uploadLrcSuccess" :show-upload-list="false"
					    :on-error="uploadLrcError">
						<Button type="ghost" icon="ios-cloud-upload-outline">上传歌词</Button>
					</Upload>
					<Input v-model="addMusicForm.lyric_file_url" disabled v-if="addMusicForm.lyric_file_url" :style="{'margin-top':injectData.edit ? '10px':'0'}"></Input>
				</FormItem>
				<FormItem label="创作时间" prop="song_create_time">
					<DatePicker type="date" placeholder="选择日期" placement="top-start" v-model="addMusicForm.song_create_time" format="yyyy-MM-dd"></DatePicker>
				</FormItem>
				<FormItem label="歌曲简介" prop="intro">
					<Input v-model="addMusicForm.intro" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="歌曲简介，最多500字" :maxlength="500"></Input>
				</FormItem>
				</Col>
			</Row>

		</Form>

		</Col>
		<Col span="8" style="padding-left:20px;">
		<div span="tree-title">选择所属目录<br/> (可展开选择，父节点不可直接勾选)
		</div>
		<Tree :data="treeShowData" ref="modalTree" :show-checkbox='true' @on-check-change="checkTree"></Tree>
		</Col>
	</Row>
</Modal>
</template>

<script>
import validate from "../../libs/validate.js";
import headerImgUploader from "../Components/headerImgUploader";
import authorSelector from "../Author_Ctrl/author-selector.vue";

export default {
	name: "addMusicModal",
	components: {
		headerImgUploader,
		authorSelector
	},
	computed: {
		user() {
			return this.$store.state.user.data
		},
		uploadMuiscUrl() {
			return this.postUrl.uploadMuiscUrl
		},

		imgUploadUrl() {
			return this.postUrl.uploadMusicImgOrLrcUrl

		},
		lrcUploadUrl() {
			return this.postUrl.uploadMusicImgOrLrcUrl
		},
	},
	props: {
		value: {
			type: Boolean,
			default: false
		},
		treeData: {
			type: Array,
			default: function() {
				return [];
			}
		},
		injectData: {
			type: Object,
			default: function() {
				return {};
			}
		}
	},
	data() {
		return {
			addMusicFormRule: {
				name: [{
					required: true,
					validator: validate.name,
					trigger: "blur"
				}],
				tone_quality_list: [{
					required: true,
					type: "array",
					min: 1,
					message: "请至少选择一种音质",
					trigger: "change"
				}],
				singer_uuid: [{
					required: true,
					message: "请选择演唱者",
					trigger: "change"
				}],
				lyric_uuid: [{
					required: true,
					message: "请选择作词者",
					trigger: "change"
				}],
				composer_uuid: [{
					required: true,
					message: "请选择作曲者",
					trigger: "change"
				}],
				intro: [{
					required: true,
					validator: validate.name,
					trigger: "blur"
				}],
				song_create_time:[{
					required: true,
					message: '请选择创作时间',
					type: 'date',
					trigger: "change"
				}]
			},
			showModal: false,
			modalLoading: true,
			musicPath: "",
			musicFileName: '',
			addMusicForm: {
				name: "",
				tone_quality_list: [
					'liuchang',
					'gaopin',
					'biaozhun',
					'wusun'
				],
				isOnline: false,
				sale_price: 0,
				song_create_time: "",
				lyric_file_url: "",
				singer_uuid: "",
				lyric_uuid: "",
				composer_uuid: "",
				intro: "",
				singer_obj: {},
				lyric_obj: {},
				composer_obj: {}
			},
			callBackTone_quality_list: '',
			uploadImgCallbackPath: "",
			uploadMusicData: {},
			uploadImgData: {},
			uploadLrcData: {},
			isUploading: false,
			uploadProgress: 0,
			selectTreeUuid: '',
			tone_qualist_all: {
				liuchang: false,
				gaopin: false,
				biaozhun: false,
				wusun: false
			},
			treeShowData: []
		};
	},
	methods: {
		/**
		 * 点击确定
		 */
		ok() {
			console.log(this.addMusicForm);
			if (!this.callBackTone_quality_list) {
				this.changeLoadingStatus(false);
				this.errorHandle("请上传音频文件！");
				return;
			}
			if (!this.uploadImgCallbackPath) {
				this.changeLoadingStatus(false);
				this.errorHandle("请先上传图片！");
				return;
			}

			if (this.injectData.edit) {
				this.updateMusicInfo()
			} else {
				this.saveMusic()
			}
		},

		saveMusic() {
			let musicMenu = this.$refs.modalTree.getCheckedNodes();
			console.log(musicMenu);
			let audioTypeList = [];
			musicMenu.forEach(type => {
				if (type.leaf_flag == '1') {
					audioTypeList.push(type.uuid)
				}
			});
			if (audioTypeList.length === 0) {
				this.errorHandle("请先选择音乐所属类型！");
				this.changeLoadingStatus(false);
				return;
			}

			this.$refs.addMusicForm.validate(valid => {
				if (!valid) {
					this.changeLoadingStatus(false);
					return
				}
				delete this.addMusicForm.wusun;
				delete this.addMusicForm.gaopin;
				delete this.addMusicForm.biaozhun;
				delete this.addMusicForm.liuchang;
				this.addMusicForm.tone_quality_list.forEach(item => {
					this.addMusicForm[item] = this.callBackTone_quality_list[item]
				});
				this.addMusicForm['md5'] = this.callBackTone_quality_list['md5']
				this.addMusicForm.is_online = this.addMusicForm.isOnline ? 1 : 0;
				let postData = JSON.parse(JSON.stringify(this.addMusicForm));
				delete postData.isOnline;
				delete postData.singer_obj;
				delete postData.lyric_obj;
				delete postData.composer_obj;
				delete postData.tone_quality_list;
				postData.token = this.user.tokenList[0];
				postData.img_url = this.uploadImgCallbackPath;
				postData.song_create_time = this.addMusicForm.song_create_time.getTime();
				postData.audio_type_uuid = audioTypeList.join(',')
				postData.shiting = this.callBackTone_quality_list.biaozhun;
				console.log(postData);
				this.http.post(this.postUrl.doAddMusicUrl, postData).then((data) => {
					console.log(data);
					if (data.code > -1) {
						this.showModal = false;
						this.$emit('add-music-sucess')
					} else {
						this.errorHandle(data.msg);

					}
				}, () => {
					this.errorHandle();

				}).then(() => {
					this.changeLoadingStatus(false);
				})
			});
		},
		updateMusicInfo() {
			// console.log(this.addMusicForm.singer_uuid,
			// 	this.addMusicForm.lyric_uuid,
			// 	this.addMusicForm.composer_uuid );
			// 	this.$refs.addMusicForm.validate()
			// this.changeLoadingStatus(false);
			// return;
			let musicMenu = this.$refs.modalTree.getCheckedNodes();
			let audioTypeList = [];
			musicMenu.forEach(type => {
				if (type.leaf_flag == '1') {
					audioTypeList.push(type.uuid)
				}
			});
			if (audioTypeList.length === 0) {
				this.errorHandle("请先选择音乐所属类型！");
				this.changeLoadingStatus(false);
				return;
			}
			this.$refs.addMusicForm.validate(valid => {
				if (!valid) {
					this.changeLoadingStatus(false);
					return
				}

				let postData = JSON.parse(JSON.stringify(this.addMusicForm));

				postData.is_online = this.addMusicForm.isOnline ? 1 : 0;
				delete postData.isOnline;
				delete postData.singer_obj;
				delete postData.lyric_obj;
				delete postData.composer_obj;
				postData.tone_qualist = this.addMusicForm.tone_quality_list.join(',');
				delete postData.tone_quality_list;
				postData.token = this.user.tokenList[0];
				postData.img_url = this.uploadImgCallbackPath;
				console.log(postData.song_create_time);
				if (typeof(this.addMusicForm.song_create_time) == 'string') {
					postData.song_create_time = new Date(this.addMusicForm.song_create_time.replace(/-/g,'/')).getTime()
				} else if (typeof(this.addMusicForm.song_create_time) == 'object') {
					postData.song_create_time = this.addMusicForm.song_create_time.getTime()
				} else if (typeof(this.addMusicForm.song_create_time) == 'number') {
					postData.song_create_time = this.addMusicForm.song_create_time
				}
				postData.audio_type_uuid = audioTypeList.join(',')
				postData.audio_uuid = this.injectData.uuid;
				console.log(postData);
				this.http.post(this.postUrl.updateMusicInfoUrl, postData).then((data) => {
					console.log(data);
					if (data.code > -1) {
						this.showModal = false;
						this.$emit('add-music-sucess')
					} else {
						this.errorHandle(data.msg);

					}
				}, () => {
					this.errorHandle();

				}).then(() => {
					this.changeLoadingStatus(false);
				})
			});

		},
		/**
		 * @param {Boolean} type
		 * 设置确定按钮loading动画，传True或者False
		 */
		changeLoadingStatus(type) {
			if (!type) {
				this.modalLoading = false;
			}
			this.$nextTick(() => {
				this.modalLoading = true;
			});
		},
		/**
		 * @param {any} data
		 * 上传图片回调
		 *
		 */
		uploadMusicSuccess(data) {
			if (data.code > -1) {
				this.callBackTone_quality_list = data.data;
				if (!this.addMusicForm.name) {
					this.addMusicForm.name = this.musicFileName.split(".wav")[0];
				}
			} else {
				this.errorHandle(data.msg);
			}
			this.isUploading = false;
		},
		uploadMusicError(e) {
			console.log("error", e);
			this.isUploading = false;
			this.errorHandle();
		},
		uploadImgSuccess(data) {
			this.uploadImgCallbackPath = data;
		},
		/**
		 * @param {File} file
		 * 获取文件，上传音乐前自动填写音乐文件名
		 *
		 */
		beforeMusicUpload(file) {
			if (this.injectData.edit) {
				this.$Notice.warning({
					title: '提示',
					desc: '如需修改音频，请重新添加！'
				});
				return false
			}

			this.musicFileName = file.name;
			this.isUploading = true;
		},
		uploadMusicProgressFunc(event) {
			this.uploadProgress = Math.round(event.percent);
		},
		handleFormatError() {
			this.isUploading = false;
			this.errorHandle("文件格式错误！");
		},
		handleMusicFormatError() {
			this.isUploading = false;
			this.errorHandle("文件格式错误！只允许.wav文件");
		},
		uploadLrcSuccess(data) {
			if (data.code > -1) {
				this.addMusicForm.lyric_file_url = data.data
			} else {
				this.errorHandle(data.msg);
			}
		},
		uploadLrcError() {
			this.errorHandle();
		},
		checkTree(item) {
			let album = [];
			for (let i = 0; i < item.length; i++) {
				if (item[i].is_album == '1') {
					album.push(item[i])
				}
			}

			if (album.length > 1) {
				for (let i = 0; i < item.length; i++) {
					if (item[i].is_album == '1') {
						this.$set(item[i], 'checked', false)
					}
				}
				this.$Notice.warning({
					title: '提示',
					desc: '只能选择一个专辑，请重新选择！'
				});
			}
		},
		queryMusicType(typeString) {
			typeString.forEach(type => {
				//pi:paentIndex
				this.treeShowData.forEach((parent, pi) => {
					if (parent.uuid == type) {
						this.$set(this.treeShowData[pi], 'checked', true)
					} else {
						if (parent.children && parent.children.length) {
							//ci:childIndex
							parent.children.forEach((child, ci) => {
								if (child.uuid == type) {
									this.$set(this.treeShowData[pi].children[ci], 'checked', true)
								}
							});
						}
					}
				});
			});
		},
		getAllToneList() {
			this.http.post(this.postUrl.getMusicAllTonequaList, {
				token: this.user.tokenList[0],
				audio_uuid: this.injectData.uuid
			}).then((data) => {
				console.log(data);
				if (data.code > -1) {
					let list = data.data.toneQualistStr.split(',');
					let typeList = data.data.audioTypelistStr.split(',');
					this.queryMusicType(typeList);
					list.forEach(item => {
						switch (item) {
							case '流畅音质':
								this.$set(this.tone_qualist_all, 'liuchang', true);
								break;
							case '标准音质':
								this.$set(this.tone_qualist_all, 'biaozhun', true);

								break;
							case '高品音质':
								this.$set(this.tone_qualist_all, 'gaopin', true);

								break;
							case '无损音质':
								this.$set(this.tone_qualist_all, 'wusun', true);

								break;
						}
					});
					console.log(this.injectData);
				}
			})
		}
	},
	created() {
		setTimeout(() => {
			//上传音频的Body
			let uploadMusicData = {
				token: this.user.tokenList[0],
				app_key: this.http.app_key,
				timestamp: "2017-09-26 15:52:28"
			};
			let uploadMusicDataSign = this.http.getSign({
				token: this.user.tokenList[0]
			});
			uploadMusicData.sign = uploadMusicDataSign;
			this.uploadMusicData = uploadMusicData;
			//上传歌词
			let uploadLrcData = {
				token: this.user.tokenList[0],
				type: 2,
				app_key: this.http.app_key,
				timestamp: "2017-09-26 15:52:28"
			}
			let uploadLrcDataSign = this.http.getSign({
				type: 2,
				token: this.user.tokenList[0]
			});
			uploadLrcData.sign = uploadLrcDataSign;
			this.uploadLrcData = uploadLrcData;
			//上传图片
			let uploadImgData = {
				token: this.user.tokenList[0],
				type: 1,
				app_key: this.http.app_key,
				timestamp: "2017-09-26 15:52:28"
			}
			let uploadImgDataSign = this.http.getSign({
				type: 1,
				token: this.user.tokenList[0]
			});
			uploadImgData.sign = uploadImgDataSign;
			this.uploadImgData = uploadImgData;
		}, 200);
	},
	watch: {
		addMusicForm:{
                handler:(val)=>{
					console.log(val);
                    //要执行的任务
                    //这里不知道怎么才能修改到this.data的数据，有知道的麻烦告知
                    //现在知道的就是通过直接修改Store.state的方式来更新数据，当然效果和修改this.data是一样的
                },
                // 深度观察
                deep:true
            },
		value(val) {
			if (this.showModal != val) {
				this.showModal = val;
				this.treeShowData = [];
			}
			if (val) {
				this.treeShowData = JSON.parse(JSON.stringify(this.treeData));
				if (this.injectData.edit) {
					this.getAllToneList();
					this.callBackTone_quality_list = 'asdasd';
					this.uploadImgCallbackPath = this.injectData.img_url;
					let yinzhiArr = this.injectData.tone_quality_list.split(",");
					for (let i = 0; i < yinzhiArr.length; i++) {
						switch (yinzhiArr[i]) {
							case '流畅音质':
								yinzhiArr[i] = 'liuchang'
								break;

							case '标准音质':
								yinzhiArr[i] = 'biaozhun'
								break;
							case '高品音质':
								yinzhiArr[i] = 'gaopin'
								break;
							case '无损音质':
								yinzhiArr[i] = 'wusun'
								break;

						}
					}
					this.addMusicForm = {
						name: this.injectData.name,
						tone_quality_list: yinzhiArr,
						isOnline: this.injectData.is_online == "1" ? true : false,
						sale_price: this.injectData.sale_price ? this.injectData.sale_price : 0,
						song_create_time: new Date(this.injectData.createtime.replace(/-/g,'/')),
						lyric_file_url: this.injectData.lyric_file_url,
						intro: this.injectData.intro,
						singer_uuid: this.injectData.singer_uuid,
						lyric_uuid: this.injectData.lyric_uuid,
						composer_uuid: this.injectData.composer_uuid,
						singer_obj: {
							name: this.injectData.singer_name,
							uuid: this.injectData.singer_uuid
						},
						composer_obj: {
							name: this.injectData.composer_name,
							uuid: this.injectData.composer_uuid
						},
						lyric_obj: {
							name: this.injectData.lyric_name,
							uuid: this.injectData.lyric_uuid
						}
					};

				}
			}
		},
		showModal(val) {
			if (val !== this.value) {
				this.$emit("input", val);
			}
			if (!val) {
				this.uploadImgCallbackPath = "";
				this.callBackTone_quality_list = "";
				this.addMusicForm = {
					name: "",
					tone_quality_list: [
						'liuchang',
						'gaopin',
						'biaozhun',
						'wusun'
					],
					isOnline: false,
					sale_price: 0,
					song_create_time: "",
					lyric_file_url: "",
					singer_uuid: "",
					lyric_uuid: "",
					composer_uuid: "",
					intro: "",
					// singer_obj: {},
					// lyric_obj: {},
					// composer_obj: {}
				};
				this.tone_qualist_all = {
					liuchang: false,
					gaopin: false,
					biaozhun: false,
					wusun: false
				}
				this.$refs.addMusicForm.resetFields()

			}
		}
	}
};
</script>

<style lang="scss">
.add-music-modal {
    .ivu-checkbox-group {
        display: flex;
        justify-content: space-around;
    }
    .ivu-modal {
        top: 20px;
        width: 80%;
        min-width: 900px;
        margin-bottom: 20px;
        .tree-title {
            font-weight: bold;
        }
    }
    .upload-music-box {
        margin-top: 10px;
        display: inline-block;
        width: 90px;
        height: 90px;
        .ivu-icon {
            width: 90px;
            height: 90px;
            &:before {
                line-height: 90px;
            }
        }
        .progress {
            text-align: center;
            position: absolute;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            line-height: 90px;
            background: rgba(255, 255, 255, 0.9);
            font-size: 24px;
            font-weight: 700;
            color: #9d9d9d;
        }
    }
    .tip-text {
        text-align: center;
        padding: 5px 0;
    }
}
</style>
